/**
 * 使用 OpenAI 库与阿里云百炼通信的客户端
 * 基于阿里云 DashScope 兼容模式
 */
const { OpenAI } = require('openai');
const { getConfig } = require('./config-manager');
const fs = require('fs').promises;

/**
 * 创建 OpenAI 客户端实例
 * @returns {OpenAI} OpenAI 客户端实例
 */
function createClient() {
  const config = getConfig();

  // 使用环境变量或默认值获取 API 密钥
  const apiKey = process.env.DASHSCOPE_API_KEY || config.alibaba_cloud_access_key_secret || 'dummy-api-key';

  // 确定使用哪个 API 端点
  let baseURL;

  if (config.use_official_api) {
    // 如果使用官方 API，则使用 DashScope 兼容模式端点
    baseURL = 'https://dashscope.aliyuncs.com/compatible-mode/v1';

    console.log('Using official DashScope compatible mode API');
  } else if (config.bailian_api_endpoint && config.bailian_api_endpoint.includes('dashscope.aliyuncs.com/compatible-mode')) {
    // 如果配置中的端点是 DashScope 兼容模式，则使用它
    baseURL = config.bailian_api_endpoint;
    console.log('Using configured DashScope compatible mode API:', baseURL);
  } else {
    // 否则使用本地服务器
    baseURL = 'http://localhost:3001/api/openai';
    console.log('Using local OpenAI compatible server');
  }
  let op = {
    baseURL,
    apiKey,
  };
  console.log("openai:..",op);
  return new OpenAI(op);
}

// 创建客户端实例
const client = createClient();

/**
 * 生成文本补全
 * @param {string} prompt - 提示文本
 * @param {number} maxTokens - 最大标记数
 * @param {number} temperature - 温度参数
 * @returns {Promise<Object>} - API 响应
 */
async function generateCompletion(prompt, maxTokens = 1024, temperature = 0.7) {
  try {
    const response = await client.chat.completions.create({
      model: getConfig().bailian_model_id || 'qwen-max',
      prompt,
      max_tokens: maxTokens,
      temperature,
    });

    // 转换为与原来的 bailian-api.js 相似的格式
    return {
      RequestId: response.id,
      Message: 'Success',
      Code: 'Success',
      Data: {
        Content: response.choices[0].text,
        TokenCount: response.usage?.completion_tokens || 0
      }
    };
  } catch (error) {
    console.error('OpenAI completion error:', error);
    throw new Error(`Failed to generate completion: ${error.message}`);
  }
}

/**
 * 生成聊天回复
 * @param {Array} messages - 消息数组
 * @param {number} maxTokens - 最大标记数
 * @param {number} temperature - 温度参数
 * @returns {Promise<Object>} - API 响应
 */
async function generateChat(messages, maxTokens = 1024, temperature = 0.7) {
  try {
    const response = await client.chat.completions.create({
      model: getConfig().bailian_model_id || 'qwen-max',
      messages,
      max_tokens: maxTokens,
      temperature,
    });

    // 转换为与原来的 bailian-api.js 相似的格式
    return {
      RequestId: response.id,
      Message: 'Success',
      Code: 'Success',
      Data: {
        Content: response.choices[0].message.content,
        TokenCount: response.usage?.completion_tokens || 0
      }
    };
  } catch (error) {
    console.error('OpenAI chat error:', error);
    throw new Error(`Failed to generate chat: ${error.message}`);
  }
}

/**
 * 分析图片
 * @param {string} imageBase64 - Base64 编码的图片数据
 * @param {string} prompt - 提示文本
 * @param {number} maxTokens - 最大标记数
 * @param {number} temperature - 温度参数
 * @returns {Promise<Object>} - API 响应
 */
async function analyzeImage(imageBase64, prompt, maxTokens = 1024, temperature = 0.7) {
  try {
    // 创建包含图片的消息
    const messages = [{
      role: 'user',
      content: [
        { type: 'text', text: prompt },
        {
          type: 'image_url',
          image_url: {
            url: imageBase64
          }
        }
      ]
    }];

    const response = await client.chat.completions.create({
      model: getConfig().bailian_model_id || 'qwen-vl-max',
      messages,
      max_tokens: maxTokens,
      temperature,
    });

    // 转换为与原来的 bailian-api.js 相似的格式
    return {
      RequestId: response.id,
      Message: 'Success',
      Code: 'Success',
      Data: {
        Content: response.choices[0].message.content,
        TokenCount: response.usage?.completion_tokens || 0
      }
    };
  } catch (error) {
    console.error('OpenAI image analysis error:', error);
    throw new Error(`Failed to analyze image: ${error.message}`);
  }
}

/**
 * 读取图片文件并转换为 base64
 * @param {string} filePath - 图片文件路径
 * @returns {Promise<string>} - Base64 编码的图片数据
 */
async function imageToBase64(filePath) {
  try {
    const data = await fs.readFile(filePath);
    return data.toString('base64');
  } catch (error) {
    console.error('Error reading image file:', error);
    throw new Error(`Failed to read image file: ${error.message}`);
  }
}

module.exports = {
  generateCompletion,
  generateChat,
  analyzeImage,
  imageToBase64
};
